process.stdout.setEncoding('utf-8');
const Excel = require('exceljs');
const { exec } = require('child_process');
const fs = require('fs');
const path = require('path');

const os = require('os');

// 获取操作系统名称
const platform = os.platform();

const FILE_URL = './logs';
const FILE_10000_URL = './logs_10000';
// 先创建下logs文件夹，避免没有报错
const files = fs.readdirSync(FILE_URL);

// 时间格式化，1、2、3、4变成01、02、03、04
function doubleStr(number) {
    return number < 10 ? '0' + number : number
}
main();
// 单次测试
async function main() {
    createFolder(FILE_URL);
    if (platform === 'win32') {
        await runCmd(`chcp 65001`);
        console.log('更新代码');
        await runCmd(`for /f "delims=" %i in ('where flutter') do @cd /d "%~dpi" && git pull`);
    }
    // 清理logs文件
    deleteAllFilesInFolder(FILE_URL);
    console.log('sqflite_test');
    await runCmd(`cd ../automated_testing_demo && flutter test ./integration_test/sqflite_test.dart --machine > ../node_test_server/${FILE_URL}/sqflite_test.txt`);
    console.log('path_provider_test');
    await runCmd(`cd ../automated_testing_demo && flutter test ./integration_test/path_provider_test.dart --machine > ../node_test_server/${FILE_URL}/path_provider_test.txt`);
    console.log('key_input_test');
    await runCmd(`cd ../automated_testing_demo && flutter test ./integration_test/key_input_test.dart --machine > ../node_test_server/${FILE_URL}/key_input_test.txt`);
    await runCmd(`timeout /t 10`);
    createXlsx(FILE_URL);
}
// 压力测试
async function pressureTest() {
    createFolder(FILE_10000_URL);
    if (platform === 'win32') {
        await runCmd(`chcp 65001`);
        console.log('更新代码');
        await runCmd(`for /f "delims=" %i in ('where flutter') do @cd /d "%~dpi" && git pull`);
    }
    // 清理logs文件
    deleteAllFilesInFolder(FILE_10000_URL);
    console.log('camera_test');
    await runCmd(`cd ../automated_testing_demo && flutter test ./integration_test/path_provider_test_10000.dart --machine > ../node_test_server/${FILE_10000_URL}/path_provider_test.txt`);
    console.log('sqflite_test');
    await runCmd(`cd ../automated_testing_demo && flutter test ./integration_test/key_input_test_10000.dart --machine > ../node_test_server/${FILE_10000_URL}/key_input_test.txt`);
    console.log('path_provider_test');
    await runCmd(`cd ../automated_testing_demo && flutter test ./integration_test/sqflite_test_10000.dart --machine > ../node_test_server/${FILE_10000_URL}/sqflite_test.txt`);
    console.log('key_input_test');
    await runCmd(`cd ../automated_testing_demo && flutter test ./integration_test/key_input_test.dart --machine > ../node_test_server/${FILE_10000_URL}/key_input_test.txt`);
    console.log('video_player_test');
    await runCmd(`cd ../automatic_video_player_test && flutter test ./integration_test/video_player_test.dart --machine > ../node_test_server/${FILE_10000_URL}/video_player_test.txt`);
    console.log('webview_flutter_test');
    await runCmd(`cd ../automatic_webview_flutter_test && flutter test ./integration_test/webview_flutter_test.dart --machine > ../node_test_server/${FILE_10000_URL}/webview_flutter_test.txt`);
    createXlsx(FILE_10000_URL);
}

// 超长时间测试
async function longTimeTest() {
    createFolder(FILE_URL);
    if (platform === 'win32') {
        await runCmd(`chcp 65001`);
        console.log('更新代码');
        await runCmd(`for /f "delims=" %i in ('where flutter') do @cd /d "%~dpi" && git pull`);
    }
    for (let i = 0; i < 1000; i++) {
        console.log('清理logs文件');
        deleteAllFilesInFolder(FILE_URL);
        console.log('sqflite_test');
        await runCmd(`cd ../automated_testing_demo && flutter test ./integration_test/sqflite_test.dart --machine > ../node_test_server/${FILE_URL}/sqflite_test.txt`);
        console.log('path_provider_test');
        await runCmd(`cd ../automated_testing_demo && flutter test ./integration_test/path_provider_test.dart --machine > ../node_test_server/${FILE_URL}/path_provider_test.txt`);
        console.log('key_input_test');
        await runCmd(`cd ../automated_testing_demo && flutter test ./integration_test/key_input_test.dart --machine > ../node_test_server/${FILE_URL}/key_input_test.txt`);
        createXlsx(FILE_URL);
    }
}

function createFolder(dirName) {
    try {
        if (!fs.existsSync(path.resolve(__dirname, dirName))) {
            fs.mkdirSync(path.resolve(__dirname, dirName), { recursive: true });
        } else {
        }
    } catch (err) {
        console.error(err);
    }
}

// 生成表格
function createXlsx(url) {
    var time = new Date();
    var dirName = (time.getMonth() + 1) + '' + doubleStr(time.getDate());
    createFolder(dirName)
    const workbook = new Excel.Workbook();
    files.forEach(async item => {
        var fileStr = fs.readFileSync(url + '/' + item, 'utf8');
        const result = fomateTxt(fileStr)
        const sheet = workbook.addWorksheet(item);
        sheet.columns = [
            { header: '测试项', key: 'testName', width: 20 },
            { header: '结果', key: 'result', width: 10 },
            { header: '运行时间(ms)', key: 'difference', width: 10 },
            { header: '打印值', key: 'message', width: 50 },
            { header: '路径', key: 'testUrl', width: 50 },
        ];
        result.forEach(item => {
            sheet.addRow(item)
        })
        // 通过流发送文件
    })

    workbook.xlsx.writeFile(dirName + '/' + doubleStr(time.getHours()) + '-' + doubleStr(time.getMinutes()) + '.xlsx');
}
// 处理txt数据
function fomateTxt(data) {
    let result = [];
    let resultMap = new Map();
    data.split('\n').forEach(item => {
        if (/^\{.*\}$/.test(item)) {
            const itemJson = JSON.parse(item);
            if (itemJson.type === 'testStart') {
                resultMap.set(itemJson.test.id, { ...itemJson, messageList: [] });
            }
            if (itemJson.testID) {
                const newItem = resultMap.get(itemJson.testID);
                newItem.difference = itemJson.time - newItem.time
                if (itemJson.type === 'testDone') {
                    newItem.result = itemJson.result;
                } else if (itemJson.type === 'print') {
                    newItem.messageList.push(itemJson.message);
                }
                resultMap.set(itemJson.testID, newItem)
            }
        }
    })
    for (let [key, mapValue] of resultMap) {
        mapValue.testName = mapValue.test.name
        mapValue.testUrl = mapValue.test.url
        mapValue.message = mapValue.messageList.join('\n');
        result.push(mapValue);
    }
    return result;
}
// 执行cmd命令
function runCmd(cmd) {
    return new Promise(function (resolve, reject) {
        console.log(cmd)
        try {
            exec(cmd, {
                maxBuffer: 1024 * 2000
            }, function (err, stdout, stderr) {
                if (err) {
                    // console.log(err);
                    reject(err);
                } else if (stderr.lenght > 0) {
                    reject(new Error(stderr.toString()));
                } else {
                    resolve();
                }
            });
        } catch (error) {
            reject(error);
        }

    });
};
// 清理文件内容
function deleteAllFilesInFolder(folderPath) {
    fs.readdirSync(folderPath).forEach(file => {
        const filePath = path.join(folderPath, file);
        fs.unlinkSync(filePath);
    });
}